<template>
  <div class="container"
       ref="imageTofile">
    <h3>设置课程基本信息</h3>
    <!--课程名称text-->
    <div class="normalinput">
      <span style="color: red; padding-top: 2px">*</span>
      <label for="inputforname">输入课程名称</label>
      <el-input id="inputforname"
                placeholder="无标题课程"
                style="width: 50%"
                v-model="coursename"></el-input>
    </div>
    <br />
    <!--班级名称text-->
    <div class="normalinput">
      <span style="color: red; padding-top: 2px">*</span>
      <label for="inputforclass">输入班级名称</label>
      <el-input id="inputforclass"
                placeholder="无标题班级"
                style="width: 50%"
                v-model="classname"></el-input>
    </div>
    <br />
    <!--开课模式radio-->
    <div class="normalinput">
      <span style="color: red; padding-top: 2px">*</span>
      <label for="selectmode">选择开课模式</label>
      <el-radio-group id="selectmode"
                      v-model="select"
                      @change="changeselect">
        <el-radio :label="0">Mooc</el-radio>
        <el-radio :label="1">SPOC</el-radio>
        <el-radio :label="2">通识</el-radio>
        <el-radio :label="3">公开课</el-radio>
      </el-radio-group>
    </div>
    <br />
    <!--课程归属单位select-->
    <div class="normalinput">
      <span style="color: red; padding-top: 2px">*</span>
      <label for="selectforunit">选择课程归属单位</label>
      <el-select id="selectforunit"
                 v-model="option1"
                 placeholder="请选择"
                 style="width: 47%"
                 @change="changeoption1">
        <el-option v-for="item in optionsfirst"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value">
        </el-option>
      </el-select>
    </div>
    <br />

    <div id="specialnull">
      <label for="ifnull"
             style="padding-top: 7px; padding-left: 50px">如无，请输入</label>
      <el-input style="width: 50%"
                id="ifnull"
                v-model="unitifnull"
                placeholder="输入课程归属单位"
                :disabled="option1 !=5"></el-input>
    </div>
    <br />
    <!--开放限制checkbox-->
    <div class="normalinput">
      <span style="color: red; padding-top: 2px">*</span>
      <label for="checkboxinput">选择开放限制</label>
      <el-checkbox-group v-model="checkList"
                         @change="changecheck">
        <el-checkbox label="check1">需选课密码</el-checkbox>
        <el-checkbox label="check2">无限制、任何人可加入</el-checkbox>
        <el-checkbox label="check3">本校学生可选</el-checkbox>
        <el-checkbox label="check4">XXXXX</el-checkbox>
      </el-checkbox-group>
    </div>
    <br />
    <!--课程归属select-->
    <div class="normalinput">
      <span style="color: red; padding-top: 2px">*</span>
      <label for="selectforcategory">选择课程归属分类</label>
      <el-select id="selectforcategory"
                 v-model="option2"
                 placeholder="请选择"
                 style="width: 47%"
                 @change="changeoption2">
        <el-option v-for="item in optionssecond"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value">
        </el-option>
      </el-select>
    </div>
    <br />
    <!--标签添加-->
    <div class="normalinput">
      <label for="selectforcategory"
             style="padding-left:50px">课程标签</label>
      <div>
        <el-tag v-for="(tag,index) in tags"
                :key="tag"
                closable
                stretch="True"
                style="margin-left:50px"
                @close="closeTag(index)">
          {{tag}}
        </el-tag>
      </div>
      <br v-if="tags.length!=0" />
      <p></p>
      <div :class="{active:tags.length==0}">

        <el-input style="width: 50%;margin-left:20px;margin-top:-30px;"
                  id="inputtag"
                  placeholder="输入后选择"
                  v-model="taginput"
                  required></el-input>
        <el-button type="success"
                   style="margin-left:30px;"
                   @click="addTag()">添加</el-button>

      </div>
    </div>
    <br />
    <!--开课时间date-->
    <div class="normalinput"
         :class="{isactive:tags.length!=0}">
      <span style="color: red; padding-top: 2px">*</span>
      <label for="selecttime">选择开课时间</label>
      <div class="block"
           id="selecttime">
        <el-date-picker v-model="date1"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        style="width:600px;margin-left:25px;"
                        @change="changedate"
                        value-format="yyyy-MM-dd">
        </el-date-picker>
      </div>
    </div>
    <br />
    <!--课时hour int-->
    <div class="normalinput">
      <span style="color: red; padding-top: 5px">*</span>
      <label for="inputnumber"
             style="padding-top: 2px">选择课时</label>
      <span style="padding-top: 2px">共</span>
      <el-input id="inputnumber"
                placeholder=0
                style="width: 50%;display:inline-block;"
                type="number"
                v-model="classnum"
                required></el-input>
      <span style="float:right;margin-right:400px;padding-top: 2px">课时</span>
    </div>
    <br />
    <div class="normalinput adjustpadding"
         style="padding:0 100px;margin-left:100px">
      <el-button type="primary">立即发布</el-button>
      <el-button type="primary"
                 style="margin-left:50px"
                 @click="submitinfo()"
                 v-loading.fullscreen.lock="fullscreenLoading">保存</el-button>
      <el-button type="primary"
                 style="margin-left:50px">星标</el-button>
      <el-button type="primary"
                 style="margin-left:50px">保存到草稿</el-button>
    </div>
    <br />
  </div>
</template>
<script>
import axios from 'axios'
import html2canvas from 'html2canvas'
import { mapState } from 'vuex'
export default {
  beforeMount() {
    this.getoneobject(this.$route.params.index) //通过路由获取数据,挂载前获取
  },

  watch: {
    $route(to, from) {
      this.getoneobject(this.$route.params.index) //通过路由获取数据,每次路由更新都获取新的数据
    },
  },
  data() {
    //基本data配置项用来展示界面和获取数据
    return {
      fullscreenLoading: false,
      coursename: '',
      classname: '',
      select: '',
      optionsfirst: [
        {
          value: '0',
          label: '教育信息技术学院',
        },
        {
          value: '1',
          label: '教师教育学院',
        },
        {
          value: '2',
          label: '教育与人类发展学院',
        },
        {
          value: '3',
          label: '计算机学院',
        },
        {
          value: '4',
          label: '大数据学院',
        },
        {
          value: '5',
          label: '其他',
        },
      ],
      option1: '',
      unitifnull: '',
      checkList: [],
      optionssecond: [
        {
          value: '0',
          label: '教育学',
        },
        {
          value: '1',
          label: '教育技术学',
        },
        {
          value: '2',
          label: '心理学',
        },
        {
          value: '3',
          label: '比较教育学',
        },
        {
          value: '4',
          label: '成人教育学',
        },
        {
          value: '5',
          label: '小学教育',
        },
      ],
      option2: '',
      tags: [],
      taginput: '',
      date1: [],
      classnum: 0,
      postobj: {},
      ...mapState(['objget']),
    }
  },
  computed: {},
  methods: {
    // 页面元素转图片
    toImage(index) {
      // 手动创建一个 canvas 标签
      const canvas = document.createElement('canvas')
      // 获取父标签，意思是这个标签内的 DOM 元素生成图片
      // imageTofile是给截图范围内的父级元素自定义的ref名称
      let canvasBox = this.$refs.imageTofile
      // 获取父级的宽高
      const width = parseInt(window.getComputedStyle(canvasBox).width)
      const height = parseInt(window.getComputedStyle(canvasBox).height)
      // 宽高 * 2 并放大 2 倍 是为了防止图片模糊
      canvas.width = width * 1
      canvas.height = height * 1
      canvas.style.width = width + 'px'
      canvas.style.height = height + 'px'
      const context = canvas.getContext('2d')
      const options = {
        backgroundColor: null,
        canvas: canvas,
        useCORS: true,
      }
      html2canvas(canvasBox, options).then((canvas) => {
        // toDataURL 图片格式转成 base64
        let dataURL = canvas.toDataURL('image/png')
        window.localStorage.setItem('li' + index, dataURL)
      })
    },

    reboot(obj) {
      //实现传入一个obj，修改data域的值重新渲染页面
      console.log(obj['unit'])
      this.coursename = obj['name']
      this.classname = obj['cname']
      this.select = obj['mode']
      if (['0', '1', '2', '3', '4'].indexOf(obj['unit']) === -1) {
        this.option1 = '5'
        this.unitifnull = obj['unit']
      } else {
        this.option1 = obj['unit']
        this.unitifnull = ''
      }
      this.option2 = obj['category']
      this.checkList = obj['limit'].split('-')
      this.tags = obj['tags'] === '' ? [] : obj['tags'].split('-')

      this.date1 = [obj['begindate'], obj['finaldate']]
      this.classnum = obj['hour']
      console.log(this.tags)
    },
    getoneobject(id) {
      //获取id如果不是create就获取数据
      if (id !== 'create') {
        var that = this
        axios.get('http://localhost:8080/backapi/classinfo/' + id).then(
          (resp) => {
            that.reboot(resp.data)
          },
          (error) => {
            this.$router.push({ path: '/page2' })
          }
        )
      } else {
        //create时候所有的重新初始化
        this.coursename = ''
        this.classname = ''
        this.select = ''
        this.option1 = ''
        this.unitifnull = ''
        this.checkList = []
        this.option2 = ''
        this.tags = []
        this.taginput = ''
        this.date1 = []
        this.classnum = 0
        this.postobj = {}
      }
    },
    addTag() {
      //增加标签
      if (this.taginput.trim().length != 0) {
        this.tags.push(this.taginput.trim())
        this.taginput = ''
      } else {
        this.$notify({
          title: '提示',
          message: '标签框中请输入文字',
          duration: 3000,
        })
      }
      console.log(this.tags.length)
    },
    //减少标签
    closeTag(index) {
      this.tags.splice(index, 1)
    },
    changedate() {
      // console.log(this.date1[0])
      // console.log(this.date1[1])
    },
    changeselect() {
      // console.log(this.select)
    },
    changeoption1() {
      // console.log(this.option1 === 5)
      // console.log(this.option1 === '5')
      this.unitifnull = ''
    },
    changeoption2() {
      console.log(this.option2)
    },
    changecheck() {
      console.log(this.checkList)
    },
    submitinfo() {
      //先进行校验
      if (this.coursename.trim().length === 0) {
        this.$notify({
          title: '提示',
          message: '请输入课程名',
          duration: 3000,
        })
      } else if (this.classname.trim().length === 0) {
        this.$notify({
          title: '提示',
          message: '请输入班级名',
          duration: 3000,
        })
      } else if ([0, 1, 2, 3].indexOf(this.select) === -1) {
        this.$notify({
          title: '提示',
          message: '请选择开课模式',
          duration: 3000,
        })
      } else if (
        this.option1.trim().length === 0 ||
        (this.option1 === '5' && !this.unitifnull.trim().length)
      ) {
        this.$notify({
          title: '提示',
          message: '请选择或者输入课程归属单位',
          duration: 3000,
        })
      } else if (this.checkList.length === 0) {
        this.$notify({
          title: '提示',
          message: '请选择开放限制',
          duration: 3000,
        })
      } else if (this.option2.trim().length === 0) {
        this.$notify({
          title: '提示',
          message: '请选择则课程归属分类',
          duration: 3000,
        })
      } else if (!this.date1[0] || !this.date1[1]) {
        this.$notify({
          title: '提示',
          message: '请选择开课的起始时间和结束时间',
          duration: 3000,
        })
      } else if (this.classnum <= 0) {
        this.$notify({
          title: '提示',
          message: '请规范输入课时',
          duration: 3000,
        })
      } else {
        if (this.unitifnull.length === 0 && this.tags.length >= 0) {
          //自主拼接postobj
          this.postobj = {
            name: this.coursename,
            cname: this.classname,
            mode: this.select,
            unit: this.option1,
            limit: this.checkList.join('-'),
            category: this.option2,
            tags: this.tags.join('-'),
            begindate: this.date1[0],
            finaldate: this.date1[1],
            hour: parseInt(this.classnum),
          }
        } else if (this.unitifnull.length !== 0 && this.tags.length >= 0) {
          this.postobj = {
            name: this.coursename,
            cname: this.classname,
            mode: this.select,
            unit: this.unitifnull,
            limit: this.checkList.join('-'),
            category: this.option2,
            tags: this.tags.join('-'),
            begindate: this.date1[0],
            finaldate: this.date1[1],
            hour: parseInt(this.classnum),
          }
        }
        if (this.$route.params.index === 'create') {
          //create就发post
          console.log(this.postobj)
          this.$store.dispatch('postobj', [this.postobj, this.toImage])
          this.fullscreenLoading = true
          setTimeout(() => {
            this.fullscreenLoading = false
            this.$router.go(0)
          }, 2000)
        } else {
          //否则发put
          console.log(this.postobj)
          this.$store.dispatch('updateobj', [
            this.postobj,
            this.$route.params.index,
          ])
          this.toImage(this.$route.params.index)
          this.fullscreenLoading = true
          setTimeout(() => {
            this.fullscreenLoading = false
            this.$router.go(0)
          }, 2000)
        }
      }
    },
  },
}
</script>
<style scoped>
h3 {
  text-align: left;
}
span {
  float: left;
}
label {
  float: left;
}
input.el-input__inner {
  float: left;
  height: 32px;
}
.normalinput {
  height: 32px;
  line-height: 32px;
}
.container {
  text-indent: 20px;
  text-align: left;
  height: fit-content;
}
#specialnull {
  font-size: 10px;
}
* >>> .el-icon-date {
  width: 50px;
}
.elselect >>> .el-range-separator {
  width: 20px;
}
/* * >>> .el-input__inner[id="selectforunit"]{
    height:40px;
}
* >>> .el-input__inner{
    height:30px;
} */
.adjustpadding {
  padding: 0 30px;
}
.isactive {
  margin-top: 50px;
  position: relative;
}
.active {
  margin-top: -100px;
  display: inline;
  width: fit-content;
}
* >>> .el-tag--light {
  margin-left: 20px !important;
}
* >>> .el-tag__close {
  text-indent: 0px;
  padding: 0 0px;
}
</style>
